package com.cpic.blood.core.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

@Slf4j
public class EncryptUtil {

    private static final String SECRET_KEY_2 = "C6Bcr2y7u7Uh37Sy";

    private IvParameterSpec ivParameterSpec;
    private SecretKeySpec secretKeySpec;
    private Cipher cipher;

    SecureRandom random = new SecureRandom();

    public EncryptUtil() {
        try {
            byte[] bytesIV = new byte[16];
            random.nextBytes(bytesIV);
            ivParameterSpec = new IvParameterSpec(bytesIV);
            secretKeySpec = new SecretKeySpec(SECRET_KEY_2.getBytes("UTF-8"), "AES");
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 加密
     *
     * @param sSrc		待加密的数据
     * @return			返回加密后的数据
     */
    public String encrypt(String sSrc){
        try {
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
            // 此处使用Base64做转码功能，同时能起到2次加密的作用。
            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param sSrc		待解密的数据
     * @return		返回解密后的数据
     */
    public String decrypt(String sSrc){
        byte[] content = sSrc.getBytes(StandardCharsets.UTF_8);
        // 判断Key是否正确
        if (content == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 先用Base64解密,因为需要解密的数据在加密之后进行了Base64二次加密
        Base64.Decoder decoder = Base64.getDecoder();
        content = decoder.decode(content);
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] original = cipher.doFinal(content);
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        EncryptUtil encryptUtil = new EncryptUtil();
        // 需要加密的内容
        String content = "请叫我dafeige";
        // 密钥的生成密码（注意：长度必须为16的整数倍）
        // 内容加密后的值
        String encode = encryptUtil.encrypt(content);
        // 被加密的内容解密后的值
        String decode = encryptUtil.decrypt(encode);
        System.out.println("encode： " + encode + "\ndecode： " + decode);
    }
}